package per.jdz.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁（写锁）
 * 共享锁（读锁）
 * ReadWriteLock
 * 读-读 可以共存
 * 读-写 不行，得写完
 * 写-写 不行
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
//        MyCache myCache = new MyCache();
        MyCacheLock myCache = new MyCacheLock();
        for (int i = 0; i < 10; i++) {
            final int t = i;
            new Thread(()-> {
                myCache.put(t + "", "temp" + t);
            }, String.valueOf(i + 1)).start();
        }
        for (int i = 0; i < 10; i++) {
            final int t = i;
            new Thread(()-> {
                myCache.get(t + "");
            }, String.valueOf(i + 1)).start();
        }
    }

}

class MyCacheLock {
    private volatile Map<String, Object> cache = new HashMap<>();
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    // 一个线程写
    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "存入"+ key + "中...");
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + "存入完成");
        } finally {
            lock.writeLock().unlock();
        }
    }

    // 所有线程可以读
    public Object get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取" + key + "中...");
            Object val = cache.get(key);
            System.out.println(Thread.currentThread().getName() + "读取" + key + "中...");
            return val;
        } finally {
            lock.readLock().unlock();
        }
    }
}

class MyCache {
    private volatile Map<String, Object> cache = new HashMap<>();

    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "存入"+ key + "中...");
        cache.put(key, value);
        System.out.println(Thread.currentThread().getName() + "存入完成");
    }

    public Object get(String key) {
        System.out.println(Thread.currentThread().getName() + "读取" + key + "中...");
        Object val = cache.get(key);
        System.out.println(Thread.currentThread().getName() + "读取" + key + "中...");
        return val;
    }
}

